<?php
class RCMSDbManager {

	protected $connections = array();
    protected $daos = array();
    protected $daoConnectionMap = array();
    
    public function connect($conName, $params) {
        $params = array_merge(array(
            'dsn'      => null,
            'user'     => '',
            'password' => '',
            'options'  => array(),
        ), $params);
        $con = new PDO($params['dsn'], $params['user'], $params['password'], $params['options']);
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->connections[$conName] = $con;
    }

    public function getConnection($conName = null){
    	return ($conName == null ) ? current($this->connections) : $this->connections[$conName];
    }

    public function setDaoConnectionMap($daoName, $conName) {
        $this->daoConnectionMap[$daoName] = $conName;
    }

    public function getConnectionForDao($daoName){
        if (isset($this->daoConnectionMap[$daoName])) {
            $conName = $this->daoConnectionMap[$daoName];
            return  $this->getConnection($coName);
        }
        return  $this->getConnection();
    }

    public function getDAO($daoName){
        if (!isset($this->daos[$daoName])) {
            $daoClass = $daoName . 'DAO';
            $con = $this->getConnectionForDao($daoName);
            $dao = new $daoClass($con);
            $this->daos[$daoName] = $dao;
        }
        return $this->daos[$daoName];
    }

    public function __destruct(){
        foreach ($this->daos as $dao) {
            unset($dao);
        }
        foreach ($this->connections as $con) {
            unset($con);
        }
    }
}
